package com.uinnova.product.eam.service.impl;

import com.binary.core.util.BinaryUtils;
import com.uinnova.product.eam.dao.PlanProcessRelationDao;
import com.uinnova.product.eam.model.es.PlanProcessRelation;
import com.uinnova.product.eam.service.PlanProcessRelationService;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class PlanProcessRelationServiceImpl implements PlanProcessRelationService {

    @Resource
    private PlanProcessRelationDao planProcessRelationDao;

    @Override
    public void saveRelation(String processInstanceId, Map<Long, Long> planIdMap) {

        for (Map.Entry<Long, Long> each : planIdMap.entrySet()) {
            PlanProcessRelation planProcessRelation = new PlanProcessRelation();
            planProcessRelation.setPlanId(each.getKey());
            planProcessRelation.setDesignPlanId(each.getValue());
            planProcessRelation.setProcessInstanceId(processInstanceId);
            planProcessRelationDao.saveOrUpdate(planProcessRelation);
        }
    }

    @Override
    public List<PlanProcessRelation> getByProcessInstanceId(String processInstanceId) {
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery()
                .must(QueryBuilders.termQuery("processInstanceId.keyword", processInstanceId));
        List<PlanProcessRelation> list = planProcessRelationDao.selectListByQuery(1, 1000, queryBuilder);
        return list;
    }

    @Override
    public PlanProcessRelation getByPlanId(Long planId) {
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery()
                .must(QueryBuilders.termQuery("planId", planId));
        List<PlanProcessRelation> list = planProcessRelationDao.selectListByQuery(1, 1, queryBuilder);
        if (BinaryUtils.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }
}
